package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.exception.file.FileSizeLimitExceededException;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.OssUtil;
import com.ruoyi.system.domain.ContractTemplate;
import com.ruoyi.system.service.IContractTemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合同模板管理
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/contractTemplate")
public class ContractTemplateController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(ContractTemplateController.class);

    @Autowired
    private IContractTemplateService contractTemplateService;

    @Autowired
    private OssUtil ossUtil;

    /**
     * 获取合同模板列表
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:list')")
    @GetMapping("/list")
    public TableDataInfo list(ContractTemplate contractTemplate)
    {
        startPage();
        List<ContractTemplate> list = contractTemplateService.selectContractTemplateList(contractTemplate);
        return getDataTable(list);
    }

    /**
     * 根据合同类型ID获取相关联的合同模板列表
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:list')")
    @GetMapping("/listByType/{typeId}")
    public AjaxResult listByType(@PathVariable("typeId") Long typeId)
    {
        List<ContractTemplate> list = contractTemplateService.selectContractTemplatesByTypeId(typeId);
        return success(list);
    }

    /**
     * 根据合同模板编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:query')")
    @GetMapping(value = "/{templateId}")
    public AjaxResult getInfo(@PathVariable Long templateId)
    {
        return success(contractTemplateService.selectContractTemplateByTemplateId(templateId));
    }

    /**
     * 新增合同模板
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:add')")
    @Log(title = "合同模板管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ContractTemplate contractTemplate)
    {
        if (!contractTemplateService.checkContractTemplateNameUnique(contractTemplate))
        {
            return error("新增合同模板'" + contractTemplate.getTemplateName() + "'失败，模板名称已存在");
        }
        contractTemplate.setCreateBy(getUsername());
        return toAjax(contractTemplateService.insertContractTemplate(contractTemplate));
    }

    /**
     * 修改合同模板
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:edit')")
    @Log(title = "合同模板管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ContractTemplate contractTemplate)
    {
        if (!contractTemplateService.checkContractTemplateNameUnique(contractTemplate))
        {
            return error("修改合同模板'" + contractTemplate.getTemplateName() + "'失败，模板名称已存在");
        }
        contractTemplate.setUpdateBy(getUsername());
        return toAjax(contractTemplateService.updateContractTemplate(contractTemplate));
    }

    /**
     * 删除合同模板
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:remove')")
    @Log(title = "合同模板管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{templateIds}")
    public AjaxResult remove(@PathVariable Long[] templateIds)
    {
        return toAjax(contractTemplateService.deleteContractTemplateByTemplateIds(templateIds));
    }

    /**
     * 上传合同模板文件
     */
//    @PreAuthorize("@ss.hasPermi('system:contractTemplate:upload')")
    @Log(title = "合同模板管理", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) throws IOException, InvalidExtensionException, FileSizeLimitExceededException, FileNameLengthLimitExceededException
    {
        if (file == null)
        {
            return error("请选择需要上传的文件");
        }

        // 检查文件类型
        String fileType = FileUploadUtils.getExtension(file);
        if (!StringUtils.equalsAnyIgnoreCase(fileType, "docx", "pdf"))
        {
            return error("文件格式不支持，请上传docx或pdf格式的文件");
        }

        try {
            // 使用阿里云OSS上传文件
            String fileUrl = ossUtil.uploadFile(file, "contract/template");

            Map<String, Object> data = new HashMap<>();
            data.put("fileId", System.currentTimeMillis());
            data.put("fileName", file.getOriginalFilename());
            data.put("fileUrl", fileUrl);
            data.put("fileType", fileType);
            data.put("fileSize", file.getSize());

            return success(data);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return error("上传文件失败：" + e.getMessage());
        }
    }

    /**
     * 下载合同模板文件
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:download')")
    @GetMapping("/download/{templateId}")
    public void download(@PathVariable Long templateId, HttpServletResponse response) throws IOException
    {
        ContractTemplate template = contractTemplateService.selectContractTemplateByTemplateId(templateId);
        if (template == null || StringUtils.isEmpty(template.getFileUrl()))
        {
            throw new RuntimeException("文件不存在");
        }

        // 处理文件下载逻辑
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=" + template.getFileName());
        ossUtil.downloadFile(template.getFileUrl(), response.getOutputStream());
    }

    /**
     * 预览合同模板文件
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:preview')")
    @GetMapping("/preview/{templateId}")
    public AjaxResult preview(@PathVariable Long templateId)
    {
        ContractTemplate template = contractTemplateService.selectContractTemplateByTemplateId(templateId);
        if (template == null || StringUtils.isEmpty(template.getFileUrl()))
        {
            return error("文件不存在");
        }

        // 获取文件类型
        String fileType = template.getFileType();
        if (StringUtils.isEmpty(fileType) && StringUtils.isNotEmpty(template.getFileName())) {
            // 如果文件类型为空但文件名不为空，从文件名获取类型
            String fileName = template.getFileName();
            fileType = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        }

        // 返回预览URL和文件类型
        String previewUrl = ossUtil.getPreviewUrl(template.getFileUrl());
        Map<String, Object> data = new HashMap<>();
        data.put("url", previewUrl);
        data.put("fileName", template.getFileName());
        data.put("fileType", fileType);
        return success(data);
    }

    /**
     * 批量导入合同模板
     */
    @PreAuthorize("@ss.hasPermi('system:contractTemplate:import')")
    @Log(title = "合同模板管理", businessType = BusinessType.INSERT)
    @PostMapping("/batchImport")
    public AjaxResult batchImport(@RequestBody List<ContractTemplate> templateList)
    {
        if (templateList == null || templateList.isEmpty())
        {
            return error("导入数据不能为空");
        }

        // 设置默认状态为正常
        for (ContractTemplate template : templateList)
        {
            template.setStatus("0");
        }

        // 批量导入
        int successCount = contractTemplateService.batchImportContractTemplates(templateList, getUsername());
        
        return success("成功导入" + successCount + "条数据");
    }
}
